package o2o.config.thirdpost.dada;

import com.google.gson.Gson;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import o2o.thridpost.dada.client.DadaApiResponse;
import o2o.thridpost.dada.client.DadaRequestParam;
import o2o.thridpost.util.CreateSignature;
import o2o.thridpost.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sunyufan deporation@qq.com
 * @date 2021/6/22 18:48
 * @description: DadaRequestClient
 */
@Component
@Slf4j
@Getter
public class DadaRequestClient {

    @Autowired
    private DadaConfig appConfig;

    public <T> DadaApiResponse callRpc(DadaRequestParam<T> requestParams, String url) {
        String requestUrl = this.appConfig.getHost().concat(url);
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();
        String str = gson.toJson(requestParams);
        map = gson.fromJson(str, map.getClass());
        map.put("body", gson.toJson(requestParams.getBody()));
        System.out.println(map);
        requestParams.setSignature(CreateSignature.createDadaSignature(map));
        try {
            map.put("signature", requestParams.getSignature());
            String resp = HttpClientUtil.postRequest(requestUrl, gson.toJson(map));
            return gson.fromJson(resp, DadaApiResponse.class);
        } catch (Exception e) {

            log.error(e.getMessage());

            return DadaApiResponse.except();
        }
    }

}
